<template>
  <div class="skuContent">
    <div class="title">
      <div class="f24 title-text jzt-shs-bold">{{ spectiDeatils.spectiDeatil.productAliasName }}</div>
      <div class="price-box">
        <div class="sku-a">
          <div class="sku-a-t jzt-shs-medium">{{ priceTure }}</div>
          <div class="sku-a-p jzt-din-bold">¥{{ priceShow }}</div>
        </div>
        <div class="sku-b">
          <div class="mr20 jzt-pf-bold">上市时间：{{ spectiDeatils.spectiDeatil.appearTime || "--" }}</div>
          <div class="mr20 jzt-pf-bold" v-show="spectiDeatils.spectiDeatil.isShowSale">
            已售：{{ spectiDeatils.spectiDeatil.businessShowSaleNum }}
          </div>
          <div class="mr20 jzt-pf-bold">
            单位：{{
              postData?.skuList?.length > 0 ? useCodeArrStore().getDictName("shop_unit", postData?.skuList[0]?.productUnit) : "--"
            }}
          </div>
        </div>
      </div>
    </div>
    <div class="specificate">
      <!-- 附加信息 -->
      <template v-if="spectiDeatils.spectiDeatil.productPrizeInfo">
        <!-- <p class="specificate-name">附加信息</p> -->
        <div class="add-info mb20 pt10 pb10 pl20 pr20">
          {{ spectiDeatils.spectiDeatil.productPrizeInfo || "-" }}
        </div>
      </template>

      <!-- 卖点 -->
      <div class="selling_point" v-if="spectiDeatils.spectiDeatil?.points?.length > 0">
        <!-- <div class="selling_point-header">卖点</div> -->
        <div class="selling_point-content">
          <ul :style="{ justifyContent: spectiDeatils.spectiDeatil.points?.length == 3 ? 'space-between' : '' }">
            <li
              :style="{
                width: spectiDeatils.spectiDeatil.points?.length == 3 ? '34.33%' : '31.33%',
                maxWidth: spectiDeatils.spectiDeatil.points?.length == 3 ? '34.33%' : '31.33%'
              }"
              v-for="(point_item, index) in spectiDeatils.spectiDeatil?.points"
              :key="index"
            >
              <div class="selling_point-content-header text-over jzt-shs-medium" :title="point_item.subjectName">
                <img src="@/assets/images/point-icon.png" alt="" width="10" class="mr10" /> {{ point_item.subjectName }}
              </div>
            </li>
          </ul>
        </div>
      </div>
      <!-- 动态规格 -->
      <div class="specificate-box" v-for="(item, i) in spectiDeatils.spectiDeatil.specificationList" :key="i">
        <div class="jzt-flex-center specificate-name-wrap jzt-pf-heavy" style="align-items: flex-start">
          <div class="specificate-name jzt-pf-heavy">{{ item.specificationName }}</div>
          <span class="jzt-pf-heavy">：</span>
        </div>

        <div class="specificate-bo">
          <div
            class="specificate-b"
            :class="{
              'disabled-wrap': itema.disable === 1,
              active: spectiDeatils.spectiDeatil.specificationList[i].showItem == b
            }"
            v-for="(itema, b) in item.children"
            :key="b"
          >
            <!--         sku   -->
            <div
              class="spe-box"
              :class="{ active: spectiDeatils.spectiDeatil.specificationList[i].showItem == b }"
              @click="addSku(item, itema, i, b, true, itema.isActive)"
            >
              <img
                class="mr10"
                v-if="itema.statsText && item.speType === specType.IMAGE_TYPE"
                :src="itema.statsText"
                alt=""
                width="24"
                height="24"
                style="border-radius: 4px"
              />

              <div
                v-if="itema.statsText && item.speType === specType.COLOR_TYPE"
                class="spe-box-img mr10"
                :style="{ 'background-color': itema.statsText }"
              ></div>
              <span class="jzt-pf-medium">{{ itema.propTemplateVal || itema.specificationVal }}</span>

              <div class="active-icon">
                <div>
                  <el-icon><Select /></el-icon>
                </div>
              </div>
            </div>
            <!--         颜色   -->
            <!-- <div
              class="spe-box-img"
              :class="{ active: spectiDeatils.spectiDeatil.specificationList[i].showItem == b }"
              :style="{ 'background-color': itema.statsText }"
              v-if="item.speType === specType.COLOR_TYPE"
            >
              <div class="mask">
                <el-tooltip :content="itema.specificationVal" placement="bottom" effect="light">{{
                  itema.specificationVal
                }}</el-tooltip>
              </div>
            </div> -->
            <!--          图片  -->
            <!-- <div
              class="spe-box-img"
              :class="{ active: spectiDeatils.spectiDeatil.specificationList[i].showItem == b }"
              v-if="item.speType === specType.IMAGE_TYPE"
            >
              <img v-if="itema.statsText" :src="itema.statsText" alt="" />
              <div class="mask">
                <el-tooltip :content="itema.specificationVal" placement="bottom" effect="light">{{
                  itema.specificationVal
                }}</el-tooltip>
              </div>
            </div> -->
          </div>
        </div>
      </div>

      <!-- 定制 -->
      <div
        class="customer-made-wrap"
        v-if="spectiDeatils.spectiDeatil.sourceType === 1 && spectiDeatils.spectiDeatil.customTemplateId !== null"
      >
        <CustomerMade
          ref="customerMadeRef"
          :postData="postData"
          :list="spectiDeatils.spectiDeatil?.customTemplate?.templateDetailList || []"
          :skuObj="skuObj"
          @returnPriceTotal="returnPriceTotal"
        />
      </div>

      <!-- 商品备注 -->
      <div class="remark-wrap">
        <ShopRemark v-model="textarea" @onBlur="onBlur" />
      </div>

      <div class="action-wrap mt32 mb16">
        <!-- 收藏 -->
        <div class="collect" v-if="$route.query?.review !== 'true'">
          <div style="height: 46px">
            <el-popover
              popper-class="collect-star-popper"
              placement="bottom"
              title=""
              :width="165"
              trigger="hover"
              content="快速收藏：默认未分组中"
            >
              <template #reference>
                <img
                  class="mg11 ml16"
                  :src="isCollect ? starActive : star"
                  alt=""
                  style="width: 24px; height: 24px"
                  @click="clickCollect"
                />
              </template>
            </el-popover>

            <el-divider direction="vertical" />
            <div class="select">
              <el-select
                v-model="collectType"
                placeholder="收藏标签"
                size="small"
                style="width: 94px"
                clearable
                multiple
                collapse-tags
                @change="styleListChange"
              >
                <el-option v-for="item in styleList" :key="item.labelId" :label="item.labelName" :value="item.labelId" />
              </el-select>
            </div>
          </div>
        </div>

        <!-- 申请模型 -->
        <div class="auth-modal-btns jzt-flex-center" v-if="$route.query?.review !== 'true'">
          <p class="jzt-pf-bold" v-if="postData?.businessModelFile?.modelFileList?.length > 0" @click="clickAuthModal(3)">
            模型下载
          </p>
          <p class="jzt-pf-bold" v-else @click="clickAuthModal(1)">申请模型</p>
        </div>

        <!-- 加入预算报价 -->
        <div
          class="join-shop"
          v-if="
            $route.query?.review !== 'true' ||
            (spectiDeatils.spectiDeatil.shopProductCompareList && spectiDeatils.spectiDeatil.shopProductCompareList.length > 0)
          "
        >
          <div
            class="btn jzt-shs-medium"
            :class="{ 'disabled-btn': !skuObj }"
            @click="
              () => {
                if (skuObj) {
                  isOpen = true;
                }
              }
            "
            v-if="$route.query?.review !== 'true'"
          >
            加入预算报价
          </div>
        </div>
      </div>

      <!-- 线上旗舰款 -->
      <div
        v-if="spectiDeatils.spectiDeatil.shopProductCompareList && spectiDeatils.spectiDeatil.shopProductCompareList.length > 0"
        class="online-wrap jzt-pf-bold"
        style="display: flex; justify-content: flex-end"
      >
        <div style="width: 200px; text-align: center">
          线上旗舰款 <span class="online" @click="openDialog">立即参与比价</span>
        </div>
      </div>
    </div>

    <!-- 申请授权弹窗 -->
    <el-dialog v-model="dialogVisibleMd" title="" :width="550" align-center>
      <h3 class="jzt-flex-center" v-if="modelDetail?.modelStatus === 2" style="line-height: 80px">已建模完成</h3>
      <div v-else style="height: 40px"></div>

      <template #header>
        <p style="color: #3d3d3d">
          模型授权信息
          <span class="f12" style="color: #86909c">（暂无模型授权信息请点击申请授权）</span>
        </p>
      </template>
      <template #footer>
        <div class="dialog-footer" style="display: flex; justify-content: center">
          <el-button v-if="modelDetail?.modelStatus === 0" class="yyx-btn" type="primary" style="width: 320px" @click="clickApply"
            >申请授权模型</el-button
          >
          <el-button v-else-if="modelDetail?.modelStatus === 1" class="yyx-btn" type="primary" disabled style="width: 320px">
            已提交申请授权模型
          </el-button>
          <el-button v-else class="yyx-btn" type="primary" style="width: 320px" @click="dialogVisibleMd = false">
            我知道了
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 模型下载 -->
    <el-dialog v-model="modelDownload" title="模型下载" width="440px" align-center>
      <div class="modelDownload">
        <div class="modelDownload_text">模型授权链接或型号</div>
        <div class="modelDownload_center">
          <el-input readonly :rows="3" :value="postData?.businessModelFile?.modelRemark" type="textarea"></el-input>
        </div>
        <div class="modelDownload_foot">
          <div
            class="modelDownload_foot_item"
            v-for="item in postData?.businessModelFile?.modelFileList || [{}, {}, {}, {}, {}]"
            :key="item.fileId"
          >
            <img src="@/assets/images/fileicon.png" style="width: 50px; height: 50px; margin-left: 8px" />
            <div class="modelDownload_footitem_center">
              <div class="modelDownload_footitem_toptext">
                <p class="text-over pr20" :title="item.fileName">
                  {{ item.fileName }}
                </p>
              </div>
              <div class="modelDownload_footitem_downtext">文件大小：{{ Math.round(item.size / 1024) }}KB</div>
            </div>
            <div class="modelDownload_foot_icon">
              <img src="@/assets/images/finish.png" style="width: 16px; height: 16px; margin-left: 8px" v-if="item === 1" />
              <img
                src="@/assets/images/xiazai.png"
                style="width: 16px; height: 16px; margin-left: 8px; cursor: pointer"
                v-else
                @click="download(item)"
              />
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 加入预算报价-抽屉 -->
    <AddBudget
      v-model:isOpen="isOpen"
      :optionInfo="optionInfo"
      :postData="postData"
      :customTotalPrice="customTotalPrice"
      :getSelectedCustom="getSelectedCustom"
    />

    <el-dialog
      v-model="dialogVisible"
      title="线上旗舰同款"
      modal-class="dialog"
      width="550"
      align-center
      @close="dialogVisible = false"
    >
      <div class="content">
        <div class="item" v-for="(item, index) in [{}, {}, {}, {}]" :key="item">
          <div class="item-head">
            <div class="item-text">线上同款{{ index + 1 }}</div>
            <div class="item-btn" @click="openUrl(item.url)">立即参与比价</div>
          </div>
          <div class="item-url">{{ item.url }}</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { reactive, onMounted, watch, ref, toRaw, nextTick } from "vue";
import { ElMessage } from "element-plus";
import { specType } from "../config";
import { getObjKeys, _throttle } from "@/utils";
import { getArrayCombine } from "@/views/home/utils";
import useCodeArrStore from "@/store/modules/select";
import ShopRemark from "./shopRemark.vue";
import AddBudget from "./addBudget.vue";
import { getCustomerRemark } from "@/apis/quote-price/following";
import { selectSpe } from "@/apis/shopHome/detail";
import CustomerMade from "./customerMade.vue";
import { Select } from "@element-plus/icons-vue";
import star from "@/assets/images/product/star.png";
import starActive from "@/assets/images/product/star_active.png";
import {
  getModelDetail,
  applyModel,
  getEnumAll,
  getLabelList,
  collectConfirm,
  collectCancel,
  addPproductLabel,
  delPproductLabel
} from "@/apis/shopHome/detail";

const emit = defineEmits(["skuChanged"]);
const customerMadeRef = ref();
const textarea = ref("");
const isOpen = ref(false);
const optionInfo = ref({ skuObj: {}, remark: "" });
const customTotalPrice = ref("0");
const collectType = ref([]);
const oldSelects = ref([]);
const styleList = ref([]); //款式风格
const isCollect = ref(0); //是否收藏 0-未收藏 1-已收藏

const props = defineProps({
  postData: Object
});

onMounted(async () => {
  const Enum = await getLabelList(); //查询收藏标签列表
  styleList.value = Enum.data;
});

/**==================================申请模型start============================================= */
const modelDownload = ref(false);
const sourceType = ref(1);
const modelDetail = ref({});
const _skuObj = ref({});
const dialogVisibleMd = ref(false);

//申请建模
const clickApply = () => {
  applyModel({
    skuId: _skuObj.value.skuId,
    applyType: props.postData?.sourceType,
    productId: props.postData?.productId
  }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "申请成功",
        type: "success",
        offset: 60
      });
      dialogVisibleMd.value = false;
    } else {
      ElMessage({
        message: res.msg,
        type: "error",
        offset: 60
      });
    }
  });
};

const clickAuthModal = async type => {
  // sourceType-1-工厂，系统授权模型
  // sourceType-2-自有，自有授权模型
  if (type == 3) {
    modelDownload.value = true;
  } else {
    sourceType.value = type;
    const __skuObj = getSkuObject();
    _skuObj.value = __skuObj;
    const res = await getModelDetail({ productId: __skuObj?.productId, applyType: type });
    res.code === 200 && (modelDetail.value = res.data);
    dialogVisibleMd.value = true;
  }
};

//模型文件下载
const download = item => {
  const a = document.createElement("a");
  let href = item.url;

  a.download = item.fileName; // 跨域不生效
  a.style.display = "none";
  a.href = href;
  document.body.appendChild(a);
  a.click();
  a.remove();
  window.URL.revokeObjectURL(href);
};
/**==================================申请模型end============================================= */

/**==================================收藏start================================================= */

//收藏标签更改
const styleListChange = async val => {
  console.log("变迁选中状态变化了===", oldSelects.value, val);
  const { added, removed } = compareArrays(oldSelects.value, val);
  console.log("add==" + added, "remove==" + removed);
  if (isCollect.value === 0) {
    // 标签选择变化时，如果是未收藏状态，则立即请求收藏接口
    await collectSubmit();
  }
  if (added.length > 0) {
    addPproductLabel({
      collectProductId: props.postData.collectId,
      labelId: added[0]
    });
  }
  if (removed.length > 0) {
    delPproductLabel({
      collectProductId: props.postData.collectId,
      labelId: removed[0]
    });
  }

  oldSelects.value = val;
};
const compareArrays = (arr1, arr2) => {
  let added = arr2.filter(element => !arr1.includes(element));
  let removed = arr1.filter(element => !arr2.includes(element));
  return { added, removed };
};
//点击收藏
const clickCollect = async () => {
  if (isCollect.value === 0) {
    collectSubmit();
  } else {
    console.log(22222);
    const res = await collectCancel({ collectProductId: props.postData.collectId });
    if (res.code === 200) {
      isCollect.value = 0;
      // 清空收藏标签的多选项
      collectType.value = [];
      oldSelects.value = [];
      ElMessage({
        message: "已取消收藏",
        offset: 60
      });
    }
  }
};
//请求收藏接口
const collectSubmit = async () => {
  const res = await collectConfirm({ collectProductId: props.postData.collectId });
  if (res.code === 200) {
    isCollect.value = 1;
    ElMessage({
      duration: 1000,
      showClose: false,
      customClass: "my-success-message",
      dangerouslyUseHTMLString: true,
      message: "<div class='img'></div><p>已将商品收藏到已设置的标签中 ~</p>"
    });
  }
};

/**==================================收藏end================================================= */

const returnPriceTotal = totalPrice => {
  customTotalPrice.value = totalPrice;
};

const getSelectedCustom = () => {
  return customerMadeRef.value?.getSelectedCustom();
};

const onBlur = html => {
  console.log("失去焦点，请求保存接口===", html);
  optionInfo.value.remark = textarea.value;
};

// TODO:优化 有时间再说
const skuObjData = ref({}); // 数据集
// 暂无作用
const keys = ref([]); // 属性集
const initSKU = sku => {
  let resultSKU = [];
  let skuKeys = getObjKeys(sku);
  for (let i in skuKeys) {
    let skuKey = skuKeys[i]; // 获取一条SKU的key
    let skuData = sku[skuKey]; // 获取一条SKU的相关数据
    let skuKeyAttrs = skuKey.split(";"); // 获取SKU的key的属性数组
    let combArr = getArrayCombine(skuKeyAttrs);

    resultSKU[skuKey] = {
      count: skuData.count,
      prices: [skuData]
    };
    // for (let j = 0; j < combArr.length; j++) {
    //   let key = combArr[j].join(";");
    //   if (resultSKU[key]) {
    //     resultSKU[key].count += skuData.count;
    //     resultSKU[key].prices.push(skuData.price);
    //   } else {
    //     resultSKU[key] = {
    //       count: skuData.count,
    //       prices: [skuData]
    //     };
    //   }
    // }
  }
  console.log("BBBBBBBB", resultSKU);
  return resultSKU;
};
const getSkuObj = data => {
  let skuObj = {};
  data.skuList?.forEach(item => {
    const properties = JSON.parse(item.properties) || [];
    const field = properties.reduce((pre, cur) => {
      return pre ? `${pre};${cur.specificationVal}` : `${pre}${cur.specificationVal}`;
    }, "");
    skuObj[field] = { ...item };
  });
  keys.value = data.specificationList?.map(item => {
    return {
      specificationName: item.specificationName,
      item: item.children.map(item => item.specificationVal)
    };
  });
  skuObjData.value = initSKU(skuObj);
};

watch(
  () => props.postData,
  newVal => {
    console.log("这是商品详情===", newVal);

    isCollect.value = newVal.collectState;
    collectType.value = newVal.collectLabelIds;
    oldSelects.value = newVal.collectLabelIds;

    const _newVal = JSON.parse(JSON.stringify(newVal));
    getSkuObj(_newVal);
    _newVal.specificationList?.forEach((item, index) => {
      item.showItem = null;
      item.children?.map((_item, _index) => {
        _item.isActive = false;
      });
    });
    spectiDeatils.spectiDeatil = _newVal;
    spectiDeatils.spectiDeatil._specificationList = newVal.specificationList;

    nextTick(() => {
      spectiDeatils.spectiDeatil.specificationList?.forEach((item, index) => {
        item.children?.map((_item, _index) => {
          if (_item.initSelect === 1) {
            addSku(item, _item, index, _index, false, _item.isActive, false);
          }
        });
      });

      // 请求接口获取置灰sku
      let activeArr = [];
      spectiDeatils.spectiDeatil.specificationList?.map(obj => {
        obj?.children?.map(_obj => {
          if (_obj.isActive) {
            activeArr.push({ ..._obj, specificationName: obj.specificationName });
          }
        });
      });
      selectSpeFun(activeArr);
    });

    //过滤卖点，标题和内容为空的数据过滤掉
    const arr = spectiDeatils.spectiDeatil?.points?.filter(item => {
      if ((item.content?.trim() !== "<p><br></p>" && item.content?.trim()) || item.subjectName?.trim()) {
        return item;
      }
    });
    spectiDeatils.spectiDeatil.points = arr;

    const skuItem = spectiDeatils.spectiDeatil?.skuList?.length ? spectiDeatils.spectiDeatil.skuList[0] : {};
    // console.log(90909090,spectiDeatils.spectiDeatil )

    // spectiDeatils.spectiDeatil.specificationList.map((item, index) => {
    //   addSku({},{}, index, 0,false,item.isActive);
    // });
    // optionInfo.value.skuObj = skuObj.value;

    // getCustomerRemarkFun(); //查询当前sku对应的备注信息
    // priceShow.value = skuItem.clinetRealPrice || 0;
    // priceTure.value = isPrice(skuItem.clinetRealPrice, skuItem.clinetPrice, skuItem.clinetPreferentialPrice);
    // console.log('这是sku值===', spectiDeatils)
  }
);

const spectiDeatils = reactive({
  spectiDeatil: []
});
// 1文字 2颜色  3图片
const SkuLists = reactive({
  SkuList: []
});
//
const priceShow = ref("");
const priceTure = ref("正价");
//点击后查找sku
// TODO: 优化
const skuObj = ref({}); //点击之后 查找出来的sku对象
const addSku = _throttle((item, itema, a, b, getRemark, isActive, selectSpe = true) => {
  let skuItemFieldArr = [],
    skuItemField = "";
  SkuLists.SkuList = [];
  item.children?.map(obj => {
    obj.isActive = false;
  });
  itema.isActive = !isActive;
  spectiDeatils.spectiDeatil.specificationList[a].showItem = null;
  if (itema.isActive) {
    spectiDeatils.spectiDeatil.specificationList[a].showItem = b;

    spectiDeatils.spectiDeatil.specificationList?.forEach(items => {
      skuItemFieldArr.push(items.children[items.showItem]?.specificationVal);
      SkuLists.SkuList.push(items.children[items.showItem]?.productSpecificationId);
    });
    skuItemField = skuItemFieldArr?.join(";") || "";
  }

  skuObj.value = skuObjData.value[skuItemField]?.prices[0];
  priceShow.value = skuObjData.value[skuItemField]?.prices[0]?.clinetRealPrice;
  priceTure.value = isPrice(
    skuObjData.value[skuItemField]?.prices[0]?.clinetRealPrice,
    skuObjData.value[skuItemField]?.prices[0]?.clinetPrice,
    skuObjData.value[skuItemField]?.prices[0]?.clinetPreferentialPrice
  );
  // console.log("选中的sku===", skuObj.value);
  if (getRemark) {
    optionInfo.value.skuObj = skuObj.value;
    // getCustomerRemarkFun(); //查询当前sku对应的备注信息
  }

  console.log("选中的sku===", skuObj.value);
  optionInfo.value.skuObj = skuObj.value;
  if (skuObj.value) {
    emit("skuChanged", skuObj.value);
    if (JSON.stringify(skuObj.value) !== "{}") {
      customerMadeRef.value?.resetCustomPrice(skuObj.value?.clinetRealPrice);
    }
  } else {
    skuObj.value = null;
    nextTick(() => {
      customerMadeRef.value?.resetCustomPrice(0);
    });
  }

  // 请求接口获取置灰sku
  let activeArr = [];
  spectiDeatils.spectiDeatil.specificationList?.map(obj => {
    obj?.children?.map(_obj => {
      if (_obj.isActive) {
        activeArr.push({ ..._obj, specificationName: obj.specificationName });
      }
    });
  });
  selectSpe && selectSpeFun(activeArr);

  /**sku匹配方案二，暂时不使用，留存备用 */
  // let propertiesArr = []
  // const _skuList = JSON.parse(JSON.stringify(spectiDeatils.spectiDeatil.skuList))
  // for (let skuItem of _skuList) {
  //   const arr = JSON.parse(skuItem.properties)
  //   skuItem.properties = arr
  //   propertiesArr.push(arr.map(proItem => proItem.specificationVal))
  //   skuItem.propertiesArr = propertiesArr
  //   for (let _arr of skuItem.propertiesArr) {
  //     if (arraysAreEqual(_arr, skuItemFieldArr)) {
  //       console.log('匹配上了===', _arr, skuItemFieldArr)
  //     }
  //   }
  // }
}, 0);

//查询置灰的sku规格数据
const selectSpeFun = activeArr => {
  const activeIds = activeArr?.map(item => item.specificationValId); //选中的规格ids
  const selectValArr = activeArr?.map(item => {
    return {
      specificationName: item.specificationName,
      selectVal: item.specificationVal
    };
  }); //选中的规格ids
  selectSpe({
    specificationList: spectiDeatils.spectiDeatil?._specificationList,
    skuList: spectiDeatils.spectiDeatil?.skuList,
    selectSpeList: selectValArr
  }).then(res => {
    if (res.code === 200) {
      //返回的带有disabled的规格数据
      let childArr = [];
      res.data.specificationList?.map(item => {
        childArr = [...childArr, ...item.children];
      });

      spectiDeatils.spectiDeatil?.specificationList?.map(item => {
        item?.children?.map(_item => {
          const currObj = childArr?.find(
            o => o.specificationValId + "=" + o.specificationVal === _item.specificationValId + "=" + _item.specificationVal
          );
          _item.disable = currObj.disable;
        });
      });
      console.log("处理后的规格===", spectiDeatils.spectiDeatil?.specificationList);
    }
  });
};

//查询当前sku对应的备注信息
const getCustomerRemarkFun = () => {
  if (skuObj.value?.id) {
    getCustomerRemark({ businessSkuId: skuObj.value?.id }).then(res => {
      if (res.code === 200) {
        textarea.value = res.msg;
        // textarea.value = String(new Date().getTime());
        optionInfo.value.remark = textarea.value; //查询的备注信息传递到预算报价抽屉组件
      }
    });
  }
};

/**
 * 判断两个数组是否相同，顺序不同
 */
const arraysAreEqual = (array1, array2) => {
  let flag = true;
  // 确保两个数组长度相同
  if (array1.length !== array2.length) {
    flag = false;
  }
  // 创建一个Set来存储array1的元素，以便快速查找
  const set1 = new Set(array1.map(item => JSON.stringify(item)));
  // 遍历array2，检查每个元素是否也在set1中
  for (const item of array2) {
    const stringifiedItem = JSON.stringify(item);
    if (!set1.has(stringifiedItem)) {
      flag = false;
    }
  }
  return flag;
};

//加入购物车的话直接用 SkuLists.SkuList的数组
//监听sku变化修改价格
watch(
  () => SkuLists.SkuList,
  newVal => {
    toRaw(spectiDeatils.spectiDeatil.skuList)?.forEach((item, i) => {
      if (isArrEqual(item.skuSpecificationList, newVal)) {
        priceShow.value = item.clinetRealPrice;
        priceTure.value = isPrice(item.clinetRealPrice, item.clinetPrice, item.clinetPreferentialPrice);
      }
    });
  }
);
const isPrice = (clinetRealPrice, clinetPrice, clinetPreferentialPrice) => {
  if (clinetRealPrice === clinetPrice) {
    return "正价";
  }
  if (clinetRealPrice === clinetPreferentialPrice) {
    return "特价";
  }
};
const isArrEqual = (arr1, arr2) => {
  return arr1?.length === arr2?.length && arr1.every(ele => arr2.includes(ele));
};

const attributesValue = reactive({
  color: "",
  size: "",
  texture: ""
});

// 生成变体组合
// const cartesianProduct = (details) => {
//     const array = details.map(item => item.children.map(itemVal => ({ name: item.specificationName, id: item.specificationId, val: itemVal })));
//     const data = [];

//     const func = (skuarr = [], i) => {
//         for (let j = 0; j < array[i].length; j++) {
//             if (i < array.length - 1) {
//                 skuarr[i] = array[i][j] // 将当前的变体选项加入 skuarr 数组中
//                 func(skuarr, i + 1) // 递归调用下一层
//             } else {
//                 data.push([...skuarr, array[i][j]])
//             }
//         }
//         return data
//     }

//     let newList = func([], 0);

//     // 开始组装每一项变体属性
//     return newList.map(item => {
//         const attributesValue = {};

//         item.forEach(({ id, val }) => {
//             attributesValue[id] = val;
//         });
//         console.log(item);
//         return {
//             attributes: item,
//             attributesValue,
//             SKU: item.map(i => i.val),
//             stock: Math.floor(Math.random() * 6), // 生成0-5的随机整数库存
//             price: 100,
//         };
//     });
// };
//计算库存
const checkInventory = (id, val) => {
  // 构造新的 attributesValue 对象
  const newAttributesValue = { ...attributesValue, [id]: val };

  for (const sku of skuList) {
    let match = true;
    for (const [key, value] of Object.entries(newAttributesValue)) {
      if (value && sku.attributesValue[key] !== value) {
        match = false;
        break;
      }
    }
    if (match && sku.stock > 0) {
      return true;
    }
  }

  return false;
};
// 返回当前点击选择后的对应sku对象
const getSkuObject = () => {
  return skuObj.value;
};

// 线上同款弹窗
const dialogVisible = ref(false);
const openDialog = () => {
  // 线上同款链接数>1，显示弹窗；=1，直接跳转链接，不打开弹窗
  let shopProductCompareList = spectiDeatils.spectiDeatil.shopProductCompareList;
  if (shopProductCompareList.length > 1) {
    dialogVisible.value = true;
  } else {
    openUrl(shopProductCompareList[0].url);
  }
};
const openUrl = url => {
  window.open(url, "_blank");
};

defineExpose({
  getSkuObject
});

onMounted(() => {});
</script>
<style lang="scss" scoped>
.action-wrap {
  display: grid;
  grid-template-columns: 160px 160px 1fr;
  gap: 20px;
}
.online-wrap {
  color: #3d3d3d;
  .online {
    color: #ff9900;
    cursor: pointer;
    border-bottom: 1px solid #ff9900;
  }
}
.auth-modal-btns {
  width: 160px;
  border: 2px solid black;
  line-height: 46px;
  border-radius: 4px;
  color: #3d3d3d;
}
.collect-star-popper {
  &.el-popper {
    font-size: 12px !important;
  }
}
.collect {
  & > div {
    display: flex;
    align-items: center;
    background-color: white;
    border-radius: 4px;
    border: 2px solid black;
    img {
      width: 20px;
      height: 20px;
      cursor: pointer;
    }
    :deep(.el-divider--vertical) {
      margin: 0;
      height: 46px;
      border-left: 2px solid black;
    }
    & > div.select {
      padding: 4px 8px 4px 0;
      :deep(.el-select__selected-item) {
        font-size: 14px;
        span {
          font-family: "PingFang-Bold" !important;
        }
      }
      :deep(.el-select__tags-text) {
        font-size: 14px;
        font-family: "PingFang-Bold" !important;
      }
      :deep(.el-select__selected-item.el-tooltip__trigger.el-tooltip__trigger) {
        .el-tag {
          padding: 0;
        }
      }
      :deep(.el-tag) {
        background-color: transparent;
        color: #3d3d3d;
      }
      :deep(.el-select__placeholder) {
        color: #3d3d3d;
      }
      :deep(.el-select__caret) {
        color: #3d3d3d;
      }
      :deep(.el-select__wrapper) {
        background-color: transparent !important;
        border: none;
        box-shadow: none;
      }
    }
  }
}
// 卖点style-begin
.selling_point {
  margin-bottom: 20px;
  &-header {
    font-size: 18px;
    color: #86909c;
  }
  &-content {
    margin-top: 10px;
    ul {
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
      li {
        border-radius: 3px;
        overflow: hidden;
        margin: 0 15px 0 0;
        max-width: 176px !important;
        width: 31.33%;
        .selling_point-content-header {
          width: auto;
          height: 40px;
          background-color: #f5f7fa;
          text-align: center;
          line-height: 40px;
          font-size: 16px;
          position: relative;
          color: #041830;
          padding: 0 16px;
          box-sizing: border-box;
          & > span {
            color: #ff8928;
          }
          &::before {
            position: absolute;
            content: "";
            width: 13px;
            height: 13px;
            background-color: white;
            border-radius: 50%;
            top: 13px;
            left: -7px;
          }
          &::after {
            position: absolute;
            content: "";
            width: 13px;
            height: 13px;
            background-color: white;
            border-radius: 50%;
            top: 13px;
            right: -7px;
          }
        }
        .selling_point-content-content {
          width: auto;
          background-color: #f5f7fa;
          padding: 20px 13px;
          overflow: hidden;
          word-wrap: break-word;
          max-height: 100px;
          overflow-y: scroll;
          font-size: 12px;
          height: 100%;
        }
      }
      li:last-child {
        margin: 0;
      }
    }
  }
}
// 卖点style-end
.skuContent {
  width: 650px;
  flex: 1;
  // max-width: 700px;

  .title {
    display: flex;
    flex-direction: column;
    padding-bottom: 20px;
    border-bottom: 1px solid #dcdfe6;

    .title-text {
      word-break: break-all;
      font-weight: 700;
      font-size: 18px;
      color: #3d3d3d;
      line-height: 32px;
      text-align: left;
      font-style: normal;
      text-transform: none;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }

    .price-box {
      display: flex;
      margin-top: 20px;
      justify-content: space-between;
      align-items: flex-end;
      .sku-a {
        display: flex;

        .sku-a-t {
          width: 58px;
          height: 24px;
          line-height: 24px;
          text-align: center;
          background: #ffffff;
          color: #ff8928;
          font-weight: 500;
          font-size: 16px;
          border-radius: 0;
          border: 1px solid #ff8928;
          margin-right: 20px;
        }

        .sku-a-p {
          font-weight: 700;
          font-size: 24px;
          color: #ff3333;
          line-height: 24px;
          text-align: left;
          font-style: normal;
          text-transform: none;
        }
      }

      .sku-b {
        display: flex;
        font-weight: 500;
        font-size: 14px;
        color: #86909c;
        line-height: 22px;
        text-align: center;
        font-style: normal;
        text-transform: none;
      }
    }
  }

  .join-shop {
    width: 100%;

    .btn {
      cursor: pointer;
      height: 50px;
      background: #041830;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: 500;
      font-size: 14px;
      color: rgba(255, 255, 255, 0.9);
      line-height: 22px;
      text-align: center;
      font-style: normal;
      text-transform: none;
      &.disabled-btn {
        background-color: #424e66;
        cursor: not-allowed;
      }
    }
  }

  .specificate {
    padding: 10px 0 20px 0;
    .specificate-name-wrap {
      span {
        font-weight: 500;
        font-size: 18px;
        color: #86909c;
        display: inline-block;
        margin-top: 4px;
      }
    }
    .specificate-name {
      font-weight: 500;
      font-size: 18px;
      color: #86909c;
      line-height: 24px;
      margin-bottom: 10px;
      text-align: left;
      cursor: pointer;
      font-style: normal;
      text-transform: none;
    }

    .add-info {
      background-color: #f5f7fa;
      color: #3d3d3d;
      line-height: 24px;
    }

    .specificate-box {
      margin-bottom: 32px;
      display: flex;
      flex-direction: column;
      display: grid;
      grid-template-columns: 102px 1fr;

      .specificate-name {
        width: 102px;
        text-align: justify;
        height: 24px;
        line-height: 24px;
        &::after {
          content: "";
          display: inline-block;
          width: 100%;
        }
      }
      .specificate-bo {
        // display: flex;
        // flex-wrap: wrap;
        display: grid;
        gap: 10px;
        grid-template-columns: 1fr 1fr;

        .specificate-b {
          display: flex;
          flex-wrap: wrap;
          border: 1px solid transparent;
          &.active {
            border: none;
          }

          .spe-box {
            // width: 317px;
            width: 100%;
            display: flex;
            align-items: center;
            cursor: pointer;
            justify-content: center;
            border-radius: 3px;
            border: 1px solid #dcdfe6;
            font-weight: 400;
            font-size: 14px;
            color: #86909c;
            // margin-right: 20px;
            padding: 5px 10px;
            line-height: 24px;
            text-align: left;
            font-style: normal;
            text-transform: none;
            position: relative;

            .active-icon {
              display: none;
              position: absolute;
              right: 0;
              bottom: 0;
              & > div {
                position: relative;
                width: 14px;
                height: 14px;
                .el-icon {
                  font-size: 12px;
                  position: absolute;
                  top: -1px;
                  left: -2px;
                  color: white;
                  transform: scale(0.7);
                }
              }
            }
            &.active {
              border: 2px solid #041830;
              .active-icon {
                border: 8px solid transparent;
                border-bottom-color: #041830;
                border-right-color: #041830;
                width: 0;
                height: 0;
                display: flex;
                align-items: flex-start;
                justify-content: flex-start;
              }
            }
          }

          &.disabled-wrap {
            cursor: not-allowed;
            .spe-box {
              pointer-events: none;
              background-color: #f9f9f9;
              color: gray;
            }
          }

          .spe-box-img {
            width: 24px;
            height: 24px;
            position: relative;

            cursor: pointer;
            border-radius: 4px;

            &.active {
              border: 1px solid #ff8928;
            }

            img {
              width: 100%;
              height: 100%;
            }

            .mask {
              display: flex;
              align-items: center;
              justify-content: center;
              position: absolute;
              bottom: 0;
              width: 90px;
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 1;
              overflow: hidden;
              text-overflow: ellipsis;
              /* 解决纯字母溢出隐藏失效*/
              word-break: break-all;
              font-weight: 400;
              font-size: 14px;
              color: #ffffff;
              line-height: 24px;
              height: 24px;
              text-align: center;
              background: linear-gradient(180deg, rgba(26, 26, 26, 0.16) 0%, #1a1a1a 100%);
              border-radius: 0;

              :deep(.el-only-child__content.el-tooltip__trigger.el-tooltip__trigger) {
                display: inline-block;
                width: 100%;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                line-height: 24px;
                height: 24px;
              }
            }
          }
        }
      }
    }

    ::-webkit-scrollbar {
      width: 12px;
      /* 设置滚动条的宽度 */
    }
  }
}
.dialog {
  .content {
    margin-top: 8px;
    max-height: 360px;
    padding-right: 10px;
    overflow-y: scroll;
    .item {
      .item-head {
        display: flex;
        justify-content: space-between;
        .item-text {
          font-size: 14px;
          color: #4e5969;
        }
        .item-btn {
          font-size: 12px;
          color: #213270;
          border-bottom: 1px solid #213270;
          cursor: pointer;
        }
      }
      .item-url {
        padding: 12px 10px;
        border-radius: 2px 2px 2px 2px;
        border: 1px solid #f2f3f5;
        text-wrap: nowrap;
        overflow-x: scroll;
        margin-top: 10px;
      }
    }
    .item + .item {
      margin-top: 20px;
    }
  }
}

.modelDownload {
  .modelDownload_text {
    margin-top: 8px;
    height: 22px;
    font-family: PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #4e5969;
    text-align: left;
  }
  .modelDownload_center {
    width: 390px;
    height: 64px;
    border-radius: 0px 0px 0px 0px;
    // border: 1px solid #e1e6ed;
    margin-top: 10px;
    :deep(.el-textarea) {
      width: 100%;
      height: 100%;
      .el-textarea__inner {
        background-color: white !important;
      }
    }
  }
  .modelDownload_foot {
    margin-top: 20px;
    height: 238px;
    overflow-y: auto;
  }
}
.modelDownload_foot_item {
  background: #f5f7fa;
  height: 66px;
  border-radius: 4px 4px 4px 4px;
  margin-bottom: 10px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-items: flex-start;
  position: relative;
  .modelDownload_foot_icon {
    position: absolute;
    top: 8px;
    right: 8px;
  }
  .modelDownload_footitem_center {
    margin-left: 10px;
  }
  .modelDownload_footitem_toptext {
    width: 300px;
    height: 22px;
    font-family: PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #3d3d3d;
    overflow: hidden; /*内容超出后隐藏*/
    text-overflow: ellipsis; /*超出内容显示为省略号*/
    white-space: nowrap; /*文本不进行换行*/
  }
  .modelDownload_footitem_downtext {
    height: 22px;
    font-family: PingFang SC;
    font-weight: 400;
    font-size: 12px;
    color: #86909c;
  }
}
.modelDownload_counter {
  // margin: 8px 81px 8px 8px;
  width: 100%;
  height: 100%;
  font-family: Source Han Sans;
  font-weight: 400;
  font-size: 14px;
  color: #86909c;
  text-align: left;
  display: flex;
  justify-content: space-evenly;
  flex-direction: column;
  overflow-y: auto;
}
</style>
